package com.ipgeocoder.messaging;


import java.util.List;

import com.ipgeocoder.model.IPInfo;
import com.ipgeocoder.util.IPGeocoderUtil;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.util.StringPool;
import com.maxmind.geoip.Location;

/**
 * <a href="IPGeocoderMessageListener.java.html"><b><i>View Source</i></b></a>
 *
 * @author Brian Wing Shun Chan
 *
 */
public class IPGeocoderMessageListener implements MessageListener {

	public void receive(Message message) {
		try {
			doReceive(message);
		}
		catch (Exception e) {
			_log.error("Unable to process message " + message, e);
		}
	}

	protected void doReceive(Message message) throws Exception {
		String ipAddress = (String)message.getPayload();

		List ipInfo = IPGeocoderUtil.getIPInfo(ipAddress);

		Object payload = StringPool.BLANK;

		if (ipInfo != null) {
			payload = JSONFactoryUtil.createJSONObject(
				JSONFactoryUtil.serialize(ipInfo));
		}

		message.setPayload(payload);

		MessageBusUtil.sendMessage(message.getResponseDestination(), message);
	}

	private static Log _log =
		LogFactoryUtil.getLog(IPGeocoderMessageListener.class);

}